package org.gateway.service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;

import lombok.AllArgsConstructor;

public class TestVolatile {

	//static  AtomicInteger j =new AtomicInteger(100);
	static  int j =100;
	Object obj = "bc";
	public static void main(String[] args) throws Exception {
		TestVolatile a = new TestVolatile();
//		TestVolatile.MyThread thread = a.new MyThread();
//		thread.start();
//		TestVolatile.MyThread thread1 = a.new MyThread();
//		thread1.start();
//		TestVolatile.MyThread thread2 = a.new MyThread();
//		thread2.start();
//		TestVolatile.MyThread thread3 = a.new MyThread();
//		thread3.start();
//		Thread.sleep(100);
//		System.out.println(j);
		ExecutorService executor = Executors.newFixedThreadPool(4);
		long start = System.currentTimeMillis();
//		Future<String> af = executor.submit(new Callable<String>() {
//
//			@Override
//			public String call() throws Exception {
//				// TODO Auto-generated method stub
//				return "123";
//			}
//		});
//		System.out.println(af.get());
		CountDownLatch begin = new CountDownLatch(1);
		CountDownLatch end = new CountDownLatch(4);
		for (int i = 0; i < 4; i++) {
			TestVolatile.MyThread thread3 = a.new MyThread(begin,end);
			executor.execute(thread3);
		}
		begin.countDown();
		end.await();
		executor.shutdownNow();
		System.out.println(j);
		System.out.println(System.currentTimeMillis()-start);
	}
	

	
	 @AllArgsConstructor
	 private class MyThread extends Thread{
		
		//private  boolean stop = true;
		/** 每个线程处理的起始数据 */
		private CountDownLatch begin;
		/** 每个线程处理的结束数据 */
		private CountDownLatch end;

		@Override
		public void run() {
			synchronized (obj) {
				
				try {
					for(int i=0;i<10000000;i++) {
						j++;
						//j.getAndIncrement();
					}
					begin.await();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}finally {
					end.countDown();
				}
			}
			
			
		}
	}
}
